package com.example.stuwork.controller;

import com.example.stuwork.common.Result;
import com.example.stuwork.pojo.Teacher;
import com.example.stuwork.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 教师管理控制器
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    /**
     * 获取所有教师
     *
     * @return 教师列表
     */
    @GetMapping
    public Result<List<Teacher>> getAllTeachers() {
        List<Teacher> teachers = teacherService.findAll();
        return Result.success("获取教师列表成功", teachers);
    }

    /**
     * 根据教师工号获取教师信息
     *
     * @param teacherId 教师工号
     * @return 教师信息
     */
    @GetMapping("/{teacherId}")
    public Result<Teacher> getTeacherById(@PathVariable String teacherId) {
        Teacher teacher = teacherService.getById(teacherId);
        if (teacher != null) {
            // 出于安全考虑，不返回密码
            teacher.setPassword(null);
            return Result.success("获取教师信息成功", teacher);
        } else {
            return Result.error("教师不存在");
        }
    }

    /**
     * 根据院系编号获取教师列表
     *
     * @param deptNumber 院系编号
     * @return 教师列表
     */
    @GetMapping("/department/{deptNumber}")
    public Result<List<Teacher>> getTeachersByDepartment(@PathVariable String deptNumber) {
        List<Teacher> teachers = teacherService.findByDeptNumber(deptNumber);
        // 出于安全考虑，清除密码字段
        teachers.forEach(teacher -> teacher.setPassword(null));
        return Result.success("获取院系教师列表成功", teachers);
    }

    /**
     * 添加教师
     *
     * @param teacher 教师信息
     * @return 添加结果
     */
    @PostMapping
    public Result<Teacher> addTeacher(@RequestBody Teacher teacher) {
        // 参数校验
        if (teacher == null) {
            return Result.error("教师信息不能为空");
        }
        
        if (StringUtils.isEmpty(teacher.getTeacherId())) {
            return Result.error("教师工号不能为空");
        }
        
        if (StringUtils.isEmpty(teacher.getPassword())) {
            return Result.error("密码不能为空");
        }
        
        if (StringUtils.isEmpty(teacher.getName())) {
            return Result.error("姓名不能为空");
        }
        
        if (StringUtils.isEmpty(teacher.getGender())) {
            return Result.error("性别不能为空");
        }
        
        if (StringUtils.isEmpty(teacher.getDeptNumber())) {
            return Result.error("院系编号不能为空");
        }

        // 检查教师是否已存在
        if (teacherService.existsTeacher(teacher.getTeacherId())) {
            return Result.error("该教师工号已存在");
        }

        boolean success = teacherService.addTeacher(teacher);
        if (success) {
            // 获取新添加的教师信息（不包含密码）
            Teacher newTeacher = teacherService.getById(teacher.getTeacherId());
            if (newTeacher != null) {
                newTeacher.setPassword(null);
            }
            return Result.success("添加教师成功", newTeacher);
        } else {
            return Result.error("添加教师失败");
        }
    }

    /**
     * 更新教师信息
     *
     * @param teacherId 教师工号
     * @param teacher   教师信息
     * @return 更新结果
     */
    @PutMapping("/{teacherId}")
    public Result<Teacher> updateTeacher(@PathVariable String teacherId, @RequestBody Teacher teacher) {
        // 参数校验
        if (teacher == null) {
            return Result.error("教师信息不能为空");
        }

        // 确保路径中的ID与请求体一致
        teacher.setTeacherId(teacherId);

        // 检查教师是否存在
        if (!teacherService.existsTeacher(teacherId)) {
            return Result.error("教师不存在");
        }

        // 密码单独更新，这里不更新密码
        teacher.setPassword(null);

        boolean success = teacherService.updateTeacher(teacher);
        if (success) {
            // 获取更新后的教师信息（不包含密码）
            Teacher updatedTeacher = teacherService.getById(teacherId);
            if (updatedTeacher != null) {
                updatedTeacher.setPassword(null);
            }
            return Result.success("更新教师信息成功", updatedTeacher);
        } else {
            return Result.error("更新教师信息失败");
        }
    }

    /**
     * 更新教师密码
     *
     * @param teacherId    教师工号
     * @param passwordInfo 密码信息
     * @return 更新结果
     */
    @PutMapping("/{teacherId}/password")
    public Result<Boolean> updatePassword(
            @PathVariable String teacherId, 
            @RequestBody PasswordUpdateRequest passwordInfo) {
        
        // 参数校验
        if (passwordInfo == null || StringUtils.isEmpty(passwordInfo.getNewPassword())) {
            return Result.error("新密码不能为空");
        }

        // 检查教师是否存在
        if (!teacherService.existsTeacher(teacherId)) {
            return Result.error("教师不存在");
        }

        boolean success = teacherService.updatePassword(teacherId, passwordInfo.getNewPassword());
        if (success) {
            return Result.success("更新密码成功", true);
        } else {
            return Result.error("更新密码失败");
        }
    }

    /**
     * 删除教师
     *
     * @param teacherId 教师工号
     * @return 删除结果
     */
    @DeleteMapping("/{teacherId}")
    public Result<Boolean> deleteTeacher(@PathVariable String teacherId) {
        // 检查教师是否存在
        if (!teacherService.existsTeacher(teacherId)) {
            return Result.error("教师不存在");
        }

        boolean success = teacherService.deleteTeacher(teacherId);
        if (success) {
            return Result.success("删除教师成功", true);
        } else {
            return Result.error("删除教师失败");
        }
    }

    /**
     * 搜索教师
     *
     * @param keyword 关键字
     * @return 教师列表
     */
    @GetMapping("/search")
    public Result<List<Teacher>> searchTeachers(@RequestParam(required = false) String keyword) {
        List<Teacher> teachers = teacherService.search(keyword);
        // 出于安全考虑，清除密码字段
        teachers.forEach(teacher -> teacher.setPassword(null));
        return Result.success("搜索教师成功", teachers);
    }

    /**
     * 密码更新请求类
     */
    static class PasswordUpdateRequest {
        private String newPassword;

        public String getNewPassword() {
            return newPassword;
        }

        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }
} 